import base64
import os
import random
import time

from django.conf import settings
from django.contrib import admin
from lxml import etree

from operation.models import Wiki


# Register your models here.
class Wikiadmin(admin.ModelAdmin):
    list_display = ('title',)
    list_filter = ('title',)
    search_fields = ('title','contentarea',)
    change_form_template = 'operation/change_wiki.html'
    
    def save_model(self, request, obj, form, change):
        tree = etree.HTML(obj.contentarea)
        images = tree.xpath("//img/@src")
        for image in images:
            imagecontent = image.split(";base64,")
            if len(imagecontent) > 1:
                imagename = str(int(time.time()*1000))+str(random.randint(1,1000))
                suffix = imagecontent[0].split("/")[1]
                imagesaveurl = os.path.join(settings.MEDIA_ROOT,imagename+"."+suffix)
                imagegeturl = "http://"+request.get_host()+os.path.join(settings.MEDIA_URL,imagename+"."+suffix)
                with open(imagesaveurl,'wb') as imagefile:
                    imagefile.write(base64.b64decode(imagecontent[1]))
                obj.contentarea = obj.contentarea.replace(image,imagegeturl)  
        admin.ModelAdmin.save_model(self, request, obj, form, change)
admin.site.register(Wiki,Wikiadmin)


